<template>
  <div class="login-page" id="login-page">
    <div class="logo-wrapper">
      <img src="../../assets/login-qax/logo.png" alt="" />
    </div>
    <div class="login-box">
      <div class="login-input">
        <div class="login-box-top">
          奇安信网神下一代网络安全综合靶场平台
        </div>
        <Divider class="login-divider" />
        <Form ref="loginForm" :model="loginForm" :rules="enterrules" class="login-form">
          <FormItem prop="username">
            <Input
              class="user"
              v-model="loginForm.username"
              size="large"
              :placeholder="$t('enterusername')"
            >
            </Input>
          </FormItem>
          <FormItem prop="password">
            <Input
              class="pass"
              :type="!passType ? 'password' : 'text'"
              password
              v-model="loginForm.password"
              size="large"
              :placeholder="$t('enterpassword')"
              autocomplete="new-password"
            >
              <div slot="suffix" @click="setPassType">
                <Icon type="ios-eye-outline" v-if="passType" />
                <Icon type="ios-eye-off-outline" v-else />
              </div>
            </Input>
          </FormItem>
          <FormItem prop="captcha" class="yanzhengma" style="display:flex;">
            <Input
              class="verify"
              v-model="loginForm.captcha"
              size="large"
              :placeholder="$t('Verificationcode')"
            >
            </Input>
            <div style="line-height: 0;">
              <Tooltip :content="$t('updateverificationcode')" placement="top" theme="dark">
                <img
                  style="width: 100%;cursor: pointer;"
                  :src="yzmPic"
                  :alt="$t('Verificationcode')"
                  @click="verification()"
                />
              </Tooltip>
            </div>
          </FormItem>
          <FormItem>
            <div class="check-wrapper">
              <!--<Checkbox v-model="remerberToken"></Checkbox>
                            {{$t('rememberMe')}}-->
              <span v-if="readMeCopy"
                ><Checkbox v-model="readMeCopy" disabled></Checkbox>我已阅读并同意</span
              ><span class="text" @click="agreementModel = true">《奇安信隐私政策声明》</span>
            </div>
          </FormItem>
          <FormItem class="submit">
            <Button
              style=""
              type="primary"
              long
              size="large"
              :loading="btnLoading"
              @click="loginButton('loginForm')"
              >{{ $t('capitalLogin') }}</Button
            >
          </FormItem>
        </Form>
      </div>
    </div>
    <Modal
      v-model="agreementModel"
      title="用户许可协议及隐私政策"
      :closable="false"
      :mask-closable="false"
      :width="800"
      footer-hide
    >
      <article class="argument-wrapper">
        <header class="argument-header">
          <p>奇安信网神下一代网络安全综合靶场平台</p>
          <p>用户许可协议</p>
        </header>
        <section v-html="argumentContent" class="argument-content"></section>
        <footer class="argument-footer-wrapper">
          <div class="check-wrapper">
            <Checkbox v-model="readMe" :disabled="readMeCopy"></Checkbox>
            我已阅读并同意《奇安信网神下一代网络安全综合靶场平台用户许可协议》
          </div>
          <Button class="comfirm-btn" :disabled="!readMe" @click="cancelModal">确定</Button>
        </footer>
      </article>
    </Modal>
  </div>
</template>

<script>
import encryption from '@/libs/encryption.js';
import cookieUse from '@/libs/cookie.js';
import { login, verCode, baseInfo, getLogoImg, queryLogoImg } from '@/api/login.js';
import { mapMutations } from 'vuex';
import argument from './argument';
export default {
  name: 'login',
  mixins: [argument],
  data() {
    return {
      fullHeight: document.documentElement.clientHeight,
      fullWidth: document.documentElement.clientWidth,
      validate: {
        user: true,
        userPrompt: '',
        pwd: true,
        pwdPrompt: '',
        yzm: true,
        yzmPrompt: ''
      },
      remerberToken: true,
      btnLoading: false,
      yzmPic: '',
      loginForm: {
        passwordInputType: 'password',
        username: '',
        password: '',
        captcha: '',
        t: '',
        key: '',
        salt: '',
        iv: ''
      },
      enterrules: {
        username: [
          { required: true, type: 'string', message: '用户名不能为空', trigger: 'change' },
          { type: 'string', min: 5, message: '用户名长度不能小于5个字符', trigger: 'change' },
          { type: 'string', max: 30, message: '用户名长度不能大于30个字符', trigger: 'change' }
        ],
        password: [{ required: true, type: 'string', message: '密码不能为空', trigger: 'change' }],
        captcha: [{ required: true, type: 'string', message: '验证码不能为空', trigger: 'change' }]
      },
      // 显示的语言
      langText: '',
      // 验证
      line1: false,
      // icon
      userNameIcon: require('../../assets/login/login-username.png'),
      pwdIcon: require('../../assets/login/login-pwd.png'),
      codeIcon: require('../../assets/login/login-code.png'),
      defYzm: require('../../assets/login/defYzm.png'),
      //眼睛状态
      passType: false,
      // 设置宽高
      contentWidth: '',
      contentHei: '',
      //logo
      loginLogo: '',
      showLoginLogo: true,
      //协议
      agreementModel: false,
      readMe: false,
      readMeCopy: false,
      logoList: []
    };
  },
  methods: {
    // 设置样式
    setStyle() {
      window.fullHeight = document.documentElement.clientHeight;
      window.fullWidth = document.documentElement.clientWidth;
      this.fullHeight = window.fullHeight;
      this.fullWidth = window.fullWidth;
      if (this.fullWidth <= 1450) {
        this.contentWidth = '761px';
        this.contentHei = '540px';
      } else if (this.fullWidth > 1450 && this.fullWidth <= 1800) {
        this.contentWidth = '817px';
        this.contentHei = '580px';
      } else if (this.fullWidth > 1800 && this.fullWidth < 2100) {
        this.contentWidth = '890px';
        this.contentHei = '630px';
      } else {
        this.contentWidth = '1152px';
        this.contentHei = '816px';
      }
    },
    // 验证码
    verification() {
      let _this = this;
      verCode()
        .then((res) => {
          if (res.data.code === 1) {
            let getData = res.data.data;
            let codeArr = [];
            for (let key in getData) {
              codeArr.push(getData[key]);
            }
            codeArr.sort();
            const t = getData['t'];
            const key = codeArr[0];
            const salt = codeArr[1];
            const iv = codeArr[2];
            _this.loginForm.t = t;
            _this.loginForm.key = key;
            _this.loginForm.salt = salt;
            _this.loginForm.iv = iv;
            _this.yzmPic = `${this.baseURL}/identity/anonymity/captcha?t=${t}`;
            _this.loginForm.captcha = '';
          } else {
            _this.yzmPic = _this.defYzm;
          }
        })
        .catch((err) => {
          _this.yzmPic = _this.defYzm;
          console.log(err);
        });
    },
    inputName() {
      let userName = this.loginForm.username;
      this.validate.user = true;
      this.userNameIcon = require('../../assets/login/login-username-fource.png');
      if (!userName) {
        this.validate.user = false;
        this.validate.userPrompt = '用户名不能为空';
        this.userNameIcon = require('../../assets/login/login-username.png');
      }
    },
    inputPWD() {
      this.validate.pwd = true;
      let userName = this.loginForm.password;
      this.pwdIcon = require('../../assets/login/login-pwd-fource.png');
      if (!userName) {
        this.validate.pwd = false;
        this.validate.pwdPrompt = '密码不能为空';
        this.pwdIcon = require('../../assets/login/login-pwd.png');
      }
    },
    inputYZM() {
      this.validate.yzm = true;
      let userName = this.loginForm.captcha;
      if (userName.length == 5) {
        this.codeIcon = require('../../assets/login/login-code-fource.png');
      } else {
        this.codeIcon = require('../../assets/login/login-code.png');
      }
      if (!userName) {
        this.validate.yzm = false;
        this.validate.yzmPrompt = '请输入验证码';
        this.codeIcon = require('../../assets/login/login-code.png');
      }
    },
    setPassType() {
      this.passType = !this.passType;
    },
    // 点击显示密码
    showPassword() {
      if (this.loginForm.passwordInputType === 'text') {
        this.loginForm.passwordInputType = 'password';
      } else {
        this.loginForm.passwordInputType = 'text';
      }
    },
    // 用户登录
    keyDown(e) {
      //如果是回车则执行登录方法
      if (e.keyCode == 13) {
        this.loginButton();
      }
    },
    ...mapMutations(['setProjectName']),
    // 登录
    loginButton() {
      let _this = this;
      _this.btnLoading = true;
      function trimStr(str) {
        return str.replace(/(^\s*)|(\s*$)/g, '');
      }
      this.$refs['loginForm'].validate((valid) => {
        if (valid) {
          let UserName = trimStr(this.loginForm.username);
          let PassWord = trimStr(this.loginForm.password);
          let key = encryption.CryptoJS.enc.Utf8.parse(this.loginForm.key);
          let iv = encryption.CryptoJS.enc.Utf8.parse(this.loginForm.iv);
          let salt = encryption.CryptoJS.enc.Utf8.parse(this.loginForm.salt);
          PassWord = encryption.Encrypt(PassWord, key, iv, salt);
          let params = {
            password: PassWord,
            username: UserName,
            rememberMe: this.remerberToken,
            t: this.loginForm.t,
            captcha: this.loginForm.captcha
          };
          login(JSON.stringify(params))
            .then((res) => {
              if (res.data.code === 1) {
                let token = res.data.data;
                let langModel = 'zh';
                if (this.langText === 'English') {
                  langModel = 'zh';
                } else {
                  langModel = 'en';
                }
                if (this.remerberToken) {
                  cookieUse.setCookie('desig-token', token, 168);
                  cookieUse.setCookie('desig-lang', langModel, 168);
                  cookieUse.setCookie('Authorization', token, 168);
                } else {
                  cookieUse.setCookie('desig-token', token, 8);
                  cookieUse.setCookie('desig-lang', langModel, 8);
                  cookieUse.setCookie('Authorization', token, 8);
                }
                this.getUserInfo();
                localStorage.setItem('token', token); // 为topo页面存储
                // 是否记住密码
                sessionStorage.setItem('desig-rm', this.remerberToken);
                this.setProjectName('qax');
                // this.setProjectName('14');
              } else {
                this.$Message.error({
                  content: res.data.message,
                  duration: 3
                });
                // 更新验证码
                this.verification();
              }
              this.btnLoading = false;
            })
            .catch((err) => {
              console.log(err);
              this.verification();
            });
        } else {
          _this.btnLoading = false;
        }
      });
    },
    // 切换语言
    // changeLang(){
    //     let val = ''
    //     if(this.langText === '中文'){
    //         val = 'zh'
    //         this.langText = 'English'
    //     }else {
    //         val = 'en'
    //         this.langText = '中文'
    //     }
    //     this.$i18n.locale = val
    //     cookieUse.setCookie('language-s',val)
    //     window.location.reload()
    // },
    // 获取用户信息
    getUserInfo() {
      let _this = this;
      baseInfo()
        .then((res) => {
          console.log(res);
          if (res.data.code === 1) {
            let userId = res.data.data.id;
            let nickname = res.data.data.nickname;
            let companyName = res.data.data.companyName;
            let companyId = res.data.data.companyId;
            let initPwd = res.data.data.initialPassword;
            let avatar = res.data.data.avatar || require('@/assets/globalIcon/defult.jpg');
            let userName = res.data.data.username;
            let type = res.data.data.type;
            // 单位管理员或者单位设计师
            let isRootDesigner;
            if (res.data.data.role && res.data.data.role === 'leader') {
              isRootDesigner = true;
            } else {
              isRootDesigner = false;
            }
            let November = {
              userId: userId,
              userName: userName,
              nickname: nickname,
              companyName: companyName,
              companyId: companyId,
              initPwd: initPwd,
              avatar: avatar,
              isRootDesigner: isRootDesigner,
              distributed: res.data.data.distributed
            };
            sessionStorage.setItem('November', encryption.SelfUseEncrypt(JSON.stringify(November)));
            _this.$router.push({
              path: '/ControlPage'
              // path: '/main'
            });
          } else {
            this.$Message.error({
              content: res.data.message,
              duration: 3
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    hideLoginLogo() {
      this.showLoginLogo = false;
    },
    // 获取系统浏览器标签的图标
    getLogo() {
      let params = {
        logoType: 'bottom',
        systemType: 'designer'
      };
      getLogoImg(params)
        .then((res) => {
          if (res.data.code === 1) {
            // this.loginLogo = '/files'+res.data.data[0].logo
            // let getData = res.data.data
            // this.loginLogo = this.getBottom(getData, this.logoList, 'bottom')
            let getData = res.data.data;
            let bottom = getData.filter((item) => item.logoType == 'bottom');
            if (bottom) {
              this.loginLogo = '/files' + bottom[0].logo;
            }
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 获取数据
    queryLogoImg() {
      let params = {
        logoType: 'bottom',
        systemType: 'designer'
      };
      queryLogoImg(params)
        .then((res) => {
          if (res.data.code == 1) {
            this.logoList = res.data.data;
            console.log('queryLogoImg ~ this.logoList:', this.logoList);
          } else {
            console.log('获取数据失败');
          }
        })
        .catch((errer) => {
          console.log('获取数据失败');
        });
    },
    getBottom(data1, data2, type) {
      let img = '';
      if (data1.length > 0 || data2.length > 0) {
        let logoType1 = data1.filter((d) => d.logoType == type); // 运维设计
        let logoType2 = data2.filter((d) => d.logoType == type); // 单位设计
        if (logoType1.length > 0 && logoType2.length > 0) {
          if (logoType1[0].hidden == 'enable' && logoType2[0].hidden == 'enable') {
            img = '/files' + logoType2[0].logo;
          } else if (logoType1[0].hidden == 'enable' && logoType2[0].hidden == 'disable') {
            img = '/files' + logoType1[0].logo;
          } else if (logoType1[0].hidden == 'disable' && logoType2[0].hidden == 'enable') {
            img = '/files' + logoType2[0].logo;
          } else if (logoType1[0].hidden == 'enable') {
            img = '/files' + logoType1[0].logo;
          } else if (logoType2[0].hidden == 'enable') {
            img = '/files' + logoType2[0].logo;
          } else {
            img = '';
          }
        } else if (logoType1.length > 0 && logoType2.length == 0) {
          if (logoType1[0].hidden == 'enable') {
            img = '/files' + logoType1[0].logo;
          }
        } else if (logoType1.length == 0 && logoType2.length > 0) {
          if (logoType2[0].hidden == 'enable') {
            img = '/files' + logoType2[0].logo;
          }
        }
      } else {
        img = '';
      }
      return img;
    },
    getName(data1, data2, type) {
      let name = '';
      let logoType1 = data1.filter((d) => d.logoType == type); // 运维设计
      let logoType2 = data2.filter((d) => d.logoType == type); // 单位设计

      if (logoType1.length > 0 && logoType2.length > 0) {
        if (logoType1[0].hidden == 'enable' && logoType2[0].hidden == 'enable') {
          name = logoType2[0].sysName;
        } else if (logoType1[0].hidden == 'enable' && logoType2[0].hidden == 'disable') {
          name = logoType1[0].sysName;
        } else if (logoType1[0].hidden == 'disable' && logoType2[0].hidden == 'enable') {
          name = logoType2[0].sysName;
        } else if (logoType1[0].hidden == 'enable') {
          name = logoType1[0].sysName;
        } else if (logoType2[0].hidden == 'enable') {
          name = logoType2[0].sysName;
        } else {
          name = '';
        }
      } else if (logoType1.length > 0 && logoType2.length == 0) {
        if (logoType1[0].hidden == 'enable') {
          name = logoType1[0].sysName;
        } else {
          name = '';
        }
      } else if (logoType1.length == 0 && logoType2.length > 0) {
        if (logoType2[0].hidden == 'enable') {
          name = logoType2[0].sysName;
        } else {
          name = '';
        }
      } else {
        name = '';
      }
      return name;
    },
    cancelModal() {
      this.agreementModel = false;
      this.readMeCopy = true;
    }
  },
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  },
  mounted() {
    // 项目
    this.setProjectName('');
    //绑定事件
    window.addEventListener('keydown', this.keyDown);
    let getToken = cookieUse.getCookie('desig-token') || '';
    let getLang = cookieUse.getCookie('language-s') || 'zh';
    if (getLang === 'zh') {
      this.langText = 'English';
    } else {
      this.langText = '中文';
    }
    //          this.getLogo()
    this.$i18n.locale = getLang;
    window.onresize = () => {
      this.setStyle();
    };
    if (getToken) {
      localStorage.setItem('token', getToken); // 为topo页面存储
      this.getUserInfo();
    } else {
      // 设置样式
      this.setStyle();
      // 验证码
      this.verification();
    }
    // this.loginLogo = `${this.baseURL}/sdn/sys/menu/sysImage?sysType=2&label=3`
  },
  created() {
    // this.queryLogoImg()
  }
};
</script>

<style scoped>
.login-page {
  width: 100%;
  height: 100%;
  min-height: 660px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: url('../../assets/login-qax/login-bg.jpg') no-repeat center center;
  background-size: 100% 100%;
}
.logo-wrapper {
  position: absolute;
  width: 100%;
  top: 0;
  padding: 10px 20px;
  background: #1b263e;
  box-shadow: 0px 2px 4px 0px rgb(0 0 0 / 10%);
  z-index: 2;
}
.login-box {
  position: relative;
  right: -28%;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 46%;
  height: 64%;
  font-size: 18px;
}
.login-box-top {
  /*font-size: 16px;*/
  width: calc(18em + 60px);
  padding: 20px 30px;
  color: #fff;
  text-align: center;
}
/deep/.login-divider.ivu-divider {
  margin: 0;
  background: #323646;
}
.login-input {
  /*font-size: 16px;*/
  width: calc(18em + 60px);
  /*max-width: 80%;*/
  background: #1a1f2e;
  border-radius: 3px;
}
.login-form {
  padding: 20px 30px;
}
.login-form .check-wrapper {
  display: flex;
  font-weight: bold;
  align-items: center;
  line-height: 1;
}
.login-form .check-wrapper span.text {
  color: #3669c3;
  margin-top: -2px;
  cursor: pointer;
}
/deep/ .login-input .ivu-input-suffix {
  height: 26px;
  margin-top: 8px;
}
/deep/ .login-input .pass .ivu-input-suffix i.ivu-icon-ios-eye-off-outline:before {
  content: '';
  display: block;
  width: 20px;
  height: 20px;
  background: url('../../assets/login-qax/icon_by.png') no-repeat;
}

/deep/ .login-input .pass .ivu-input-suffix i.ivu-icon-ios-eye-outline:before {
  content: '';
  display: block;
  width: 20px;
  height: 20px;
  background: url('../../assets/login-qax/icon_open.png') no-repeat;
}
/deep/ .submit button {
  border-right: none;
  background-image: linear-gradient(#4290ff, #2f70ff);
  box-shadow: 0px 6px 18px rgba(47, 112, 255, 0.25) !important;
  border-radius: 3px;
}
/deep/ .login-input .ivu-input {
  height: 40px;
  color: #333 !important;
  border: 1px solid rgba(255, 255, 255, 0.3) !important;
  background: transparent;
  border-radius: 3px;
}
/deep/ .login-input .ivu-input::-webkit-input-placeholder {
  color: rgba(255, 255, 255, 0.3) !important;
}
/deep/ .login-input .ivu-input:hover {
  border: 1px solid #4a2ed1;
}
/deep/ .login-input .ivu-input:focus {
  box-shadow: none !important;
  /*box-shadow:0px 0px 8px rgb(167, 153, 218);
        border: 1px solid rgb(167, 153, 218);
        color: rgb(167, 153, 218)!important;*/
}
/deep/ .login-input .ivu-form-item-error .ivu-input {
  border: 1px solid #ed4014;
}
/deep/ .login-input .ivu-form-item-error .ivu-input:focus {
  /* border: 1px solid #ed4014; */
  box-shadow: 0px 0px 8px rgb(237, 64, 20, 0.6);
}
/deep/ .verify {
  flex: auto;
  margin-right: 10px;
}
/deep/ .yanzhengma .ivu-form-item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
/deep/ .ivu-btn-primary {
  color: #fff !important;
}
.langWrap .ivu-btn-ghost.ivu-btn-dashed {
  color: rgba(255, 255, 255, 0.6);
  border-color: rgba(255, 255, 255, 0.6);
}
.langWrap .ivu-btn-ghost.ivu-btn-dashed:hover {
  color: #57a3f3;
  border-color: #57a3f3;
}
.argument-wrapper {
  /*font-size:14px;*/
}
.argument-header {
  margin-bottom: 10px;
  font-size: 14px;
  text-align: center;
  font-weight: bold;
}
.argument-content {
  line-height: 1.5;
  height: 50vh;
  overflow: auto;
  font-size: 12px;
}
.argument-footer-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}
.argument-footer-wrapper .check-wrapper {
  display: flex;
  color: #666666;
}
.comfirm-btn {
  background: #2e6be6;
  color: #fff;
}
.comfirm-btn:disabled {
  opacity: 0.3;
}
.comfirm-btn:disabled:hover {
  background: #2e6be6;
  color: #fff;
  opacity: 0.3;
}
.comfirm-btn {
  background: #2e6be6;
  color: #fff;
}
</style>
<style>
#login-page .login-input .ivu-input {
  color: #fff !important;
}
#login-page .login-input .ivu-input::-webkit-input-placeholder {
  color: rgba(255, 255, 255, 0.3) !important;
}
#login-page .ivu-checkbox-checked .ivu-checkbox-inner {
  border-color: transparent;
}
.argument-content p {
  margin: 10px 0;
}
.argument-content td {
  padding: 5px;
}
</style>
